package LeetCode_SingleLinkedlist;

/**
 * Created with IntelliJ IDEA.
 * Description:如果链表中有环，返回相交的节点，如果没有环，返回null
 * User: 阿宾
 * Date: 2024-11-11
 * Time: 09:48
 */
public class Demo9 {
    static class ListNode {
        int val;
        ListNode next;

        public ListNode(int val) {
            this.val = val;
        }
        public ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode detectCycle(ListNode head) {
        if(head == null || head.next == null){
            return null;
        }
        ListNode fast = head;
        ListNode slow = head;
        while(fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
            if(fast == slow){
                break;
            }
        }
        //跳出循环有两种
        if(fast == null || fast.next == null){
            return null;
        }
        //此时说明有环
        slow = head;
        while(slow != fast){
            slow = slow.next;
            fast = fast.next;
        }
        return slow;
    }

}
